package com.studyroom.service.impl;

import com.studyroom.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Service
public class FileServiceImpl implements FileService {
    
    @Value("${file.upload.path:../}")
    private String uploadPath;

    @Override
    public String saveFile(MultipartFile file, String path, String fileName) throws IOException {
        // 获取项目根目录
        String projectRoot = new File(uploadPath).getAbsolutePath();
        log.info("项目根目录: {}", projectRoot);
        
        // 构建完整的存储路径
        String fullPath = projectRoot + path;
        log.info("完整存储路径: {}", fullPath);
        
        // 确保目录存在
        Path dirPath = Paths.get(fullPath);
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
        }

        // 保存文件
        String filePath = fullPath + fileName;
        File dest = new File(filePath);
        file.transferTo(dest);
        
        log.info("文件保存成功: {}", filePath);
        
        // 返回访问路径
        return path + fileName;
    }
} 